import 'package:bike_ride/api/common_repository.dart';
import 'package:bike_ride/common/mvvm/base_view_model.dart';
import 'package:bike_ride/common/widget/dialog/m_dialog.dart';
import 'package:bike_ride/common/widget/notifier_widget.dart';
import 'package:bike_ride/main/app.dart';
import 'package:bike_ride/model/cyling/model/unpay_info_m.dart';
import 'package:bike_ride/model/mine/model/finance_stat_m.dart';
import 'package:bike_ride/model/pay/model/overseas_pay_m.dart';
import 'package:bike_ride/model/pay/model/payed_order_detail_m.dart';
import 'package:bike_ride/model/pay/view/pay_v.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class PayViewModel extends PageViewModel<PayViewState> {
  CancelToken? cancelToken;

  late String orderId;
  UnPayInfoM? unPayInfoM;
  DiscountStatM? discountStatM;
  bool paySuccess = false;
  OverseasPayM? overseasPayM;
  PayedOrderDetailM? payedOrderDetailM;

  //是否从cycling页面跳转过来
  bool formCyclingPage(){
    return pageRouteObserver?.getRouteStackPath().contains(Routers.cyclingView)??false;
  }

  @override
  onCreate() {
    cancelToken = CancelToken();
    pageDataModel = PageDataModel();
    unPayInfoM = state.widget.arguments['model'];
    orderId = state.widget.arguments['order_id'];
    if(unPayInfoM == null){
      getUnPayInfo(orderId);
    }
    getFinanceInfo();
  }

  @override
  onDispose() {
    if (!(cancelToken?.isCancelled ?? true)) {
      cancelToken?.cancel();
    }
    super.onDispose();
  }



  Future getUnPayInfo(String? orderId) async {
    unPayInfoM = await CommonRepository.getUnPayInfoIdl(
        cancelToken: cancelToken, orderId: orderId);
    if(unPayInfoM?.paystatus == 1 && unPayInfoM?.amount == 0 || [3,4,5].contains(unPayInfoM?.orderStatus)){
      //0元订单
      paySuccess = true;
      if(formCyclingPage()){
        showPaySuccessDialog();
      }
      getFinishOrderDetail(orderId);
    }
    state.notifyChange();
  }


  Future getFinanceInfo() async {
    discountStatM = await CommonRepository.getFinanceInfoIdl(
        cancelToken: cancelToken);
    state.notifyChange();
  }

  Future getFinishOrderDetail(String? orderId) async {
    EasyLoading.show();
    final result = await CommonRepository.getFinishOrderDetailIdl(
        cancelToken: cancelToken, orderId: orderId);
    EasyLoading.dismiss();
    payedOrderDetailM = result;
    state.notifyChange();
  }

  /// 请求数据
  @override
  Future<PageViewModel?> requestData({Map<String, dynamic>? params}) async {
    return null;

  }
}